package com.zw.transition.controller;


import com.zw.transition.base.BaseController;
import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.*;
import com.zw.transition.services.AssemblyService;
import com.zw.transition.services.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private IndexService indexService;
    @Autowired
    private AssemblyService assemblyService;

    /**
     * 跳转到首页
     */
    @GetMapping("/index")
    public String index(Model model) {
//        model.addAttribute("hisApply", indexService.findHisApplyList());
//        model.addAttribute("hisRec", indexService.findHisRecList());
//        model.addAttribute("hisCheck", indexService.findHisCheckList());
        return "/index";
    }

    /**
     * 跳转到历史申请
     */
    @GetMapping("/hisApply")
    public String hisApply(Model model) {
        model.addAttribute("hisApply", indexService.findHisApplyList());
        return "/historicalApply";
    }

    /**
     * 跳转到历史接收
     */
    @GetMapping("/hisRec")
    public String hisRec(Model model) {
        model.addAttribute("hisRec", indexService.findHisRecList());
        return "/historicalRec";
    }

    /**
     * 跳转到历史质检
     */
    @GetMapping("/hisCheck")
    public String hisCheck(Model model) {
        model.addAttribute("hisCheck", indexService.findHisCheckList());
        return "/historicalCheck";
    }

    /**
     * 修改密码
     */
    @ResponseBody
    @PostMapping("/upp")
    public JsonResult uup(String pwd, HttpSession session) {
        User user = (User) session.getAttribute("user");
        user.setPwd(pwd);
        return jsonResult(indexService.updatePwd(user));
    }

    /**
     * 扫码
     */
    @GetMapping("/scan/{type}")
    public String scan(@PathVariable("type") Integer type, Model model) {
        model.addAttribute("type", type);
        return "scan";
    }

    /**
     * 申请，接收页面
     */
    @GetMapping("/result/{type}/{code}")
    public String scan(@PathVariable("type") Integer type, @PathVariable("code") String code, Model model) {
        try {
            model.addAttribute("url", "/scan/" + type);
            if (code != null) {
                code = code.replace("◐", "/");
                code = code.replace("◑", "/");
            }
            String content = "";
            FlowSheet sheet = indexService.findSheet(code);
            FlowRoute firstRoute = null;
            if (sheet == null) {
                model.addAttribute("content", "该工艺卡未接收！");
            } else {
                firstRoute = indexService.getFirstFlowRouteBySheetId(sheet.getId());
                if (firstRoute != null && "原料".equals(firstRoute.getRoute()) && firstRoute.getOrderNo() == 10) {
                    if (firstRoute.getMayApplyNum() == 0 &&
                            firstRoute.getApplyNum() == 0 &&
                            firstRoute.getCheckNum() == 0) {
                        content = "该序为原料，待下料！";
                    } else {

                    }
                } else if (firstRoute != null && firstRoute.getOrderNo() == 10 &&
                        firstRoute.getMayApplyNum() == 0 &&
                        firstRoute.getApplyNum() == 0 &&
                        firstRoute.getCheckNum() == 0) {
                    content = "该序为" + firstRoute.getRoute() + "，待下料！";
                } else if (firstRoute == null) {
                    content = "该零件已全部转序！";
                }
            }
            model.addAttribute("sheet", indexService.findSheet(code));
            if (type == 1) {
                // 申请质检
                if (firstRoute != null && firstRoute.getOrderNo() != 10) {
                    if (firstRoute != null && firstRoute.getRecNum() == 0) {
                        content = "该序为" + firstRoute.getRoute() + "，待接收！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() != 0 && firstRoute.getCheckNum() < firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，待质检！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() != 0 && firstRoute.getCheckNum().intValue() == firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，已接收！";
                    }
                }else   if (!firstRoute.getRoute().equals("原料") && firstRoute.getOrderNo() == 10) {
                     if (firstRoute != null &&  firstRoute.getCheckNum() < firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，待质检！";
                    }
                } else if (firstRoute == null) {
                    content = "该零件已全部转序！";
                }
                List<FlowRoute> list = indexService.findApplyList(code);
                if (list.size() > 0) {
                    List<FlowRoute> completeList = indexService.findCompleteApplyList1(code);
                    model.addAttribute("list", list);
                    //model.addAttribute("completeList", completeList);
                }
                if (!"".equals(content)) {
                    model.addAttribute("content", content);
                }
                return "apply";
            } else if (type == 2) {
                // 质检
                if (firstRoute != null && firstRoute.getOrderNo() != 10) {
                    if (firstRoute != null && firstRoute.getRecNum() == 0) {
                        content = "该序为" + firstRoute.getRoute() + "，待接收！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() == 0) {
                        content = "该序为" + firstRoute.getRoute() + "，待申请质检！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() != 0 && firstRoute.getCheckNum().intValue() == firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，已接收！";
                    }
                } else if (firstRoute == null) {
                    content = "该零件已全部转序！";
                }
                List<FlowModel> list = indexService.findCheckList(code);
                if (list.size() > 0) {
                    List<FlowRoute> completeList = indexService.findCompleteApplyList2(code);
                    model.addAttribute("list", list);
                } else if (!"".equals(content)) {
                    model.addAttribute("content", content);
                }
                //model.addAttribute("completeList", completeList);
                return "check";
            } else if (type == 3) {
                // 转序接收
                if (firstRoute != null && firstRoute.getOrderNo() != 10) {
                    if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() != 0 && firstRoute.getCheckNum() < firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，待质检！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() == 0) {
                        content = "该序为" + firstRoute.getRoute() + "，待申请质检！";
                    } else if (firstRoute != null && firstRoute.getRecNum() != 0 && firstRoute.getApplyNum() != 0 && firstRoute.getCheckNum().intValue() == firstRoute.getApplyNum()) {
                        content = "该序为" + firstRoute.getRoute() + "，已接收！";
                    }
                } else if (firstRoute == null) {
                    content = "该零件已全部转序！";
                }
                List<FlowModel> list = indexService.findRecList(code);
                if (list.size() > 0) {
                    List<FlowRoute> completeList = indexService.findCompleteApplyList(code);
                    model.addAttribute("list", list);
                } else if (!"".equals(content)) {
                    model.addAttribute("content", content);
                }
                return "rec";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }


    /**
     * 申请质检
     */
    @ResponseBody
    @PostMapping("/apply")
    public JsonResult apply(FlowRoute route) {
        return indexService.apply(route);
    }

    /**
     * 质检驳回
     */
    @ResponseBody
    @PostMapping("/reject")
    public JsonResult reject(FlowTrans trans) {
        return jsonResult(indexService.reject(trans));
    }

    /**
     * 质检合格
     */
    @ResponseBody
    @PostMapping("/success")
    public JsonResult success(FlowTrans trans) {
        return jsonResult(indexService.success(trans));
    }

    /**
     * 接收
     */
    @ResponseBody
    @PostMapping("/rec")
    public JsonResult rec(FlowTrans trans) {
        return jsonResult(indexService.rec(trans));
    }

    /**
     * 历史申请
     */
    @ResponseBody
    @GetMapping("/his/apply")
    public JsonResult hisApply() {
        List<FlowModel> list = indexService.findHisApplyList();
        return success().setData(list);
    }

    /**
     * 删除
     */
    @ResponseBody
    @PostMapping("/delApply")
    public JsonResult delApply(Integer id, Integer tranType) {
        int rc = 0;
        if (tranType.compareTo(1) == 0) {
            /** 生产转序 **/
            rc = indexService.delApply(id);
        } else if (tranType.compareTo(2) == 0) {
            /** 装配转序 **/
            rc = assemblyService.delApply(id);
        }
        return jsonResult(rc);
    }

    /**
     * 重新申请
     */
    @ResponseBody
    @PostMapping("/repeatApply")
    public JsonResult repeatApply(Integer id, Integer tranType) {
        int rc = 0;
        if (tranType.compareTo(1) == 0) {
            /** 生产转序 **/
            rc = indexService.repeatApply(id);
        } else if (tranType.compareTo(2) == 0) {
            /** 装配转序 **/
            rc = assemblyService.repeatApply(id);
        }
        return jsonResult(rc);
    }

    /**
     * 历史接收
     */
    @ResponseBody
    @GetMapping("/his/rec")
    public JsonResult hisRec() {
        List<FlowModel> list = indexService.findHisRecList();
        return success().setData(list);
    }

    /**
     * 撤销接收
     */
    @ResponseBody
    @PostMapping("/cancel/rec")
    public JsonResult cancelRec(FlowTrans trans) {
        int rc = 0;
        if (trans.getTranType().compareTo(1) == 0) {
            rc = indexService.cancelRec(trans);
        } else if (trans.getTranType().compareTo(2) == 0) {
            rc = assemblyService.cancelRec(trans);
        }
        return jsonResult(rc);
    }

    /**
     * 撤销申请
     */
    @ResponseBody
    @PostMapping("/cancel/apply")
    public JsonResult cancelApply(FlowTrans trans) {

        if (trans.getTranType().compareTo(1) == 0) {
            /** 生产转序 **/
            //当前转序单
            FlowTrans flowTrans = indexService.getTrans(trans.getId());
            //当前路线
            FlowRoute currentFlowRoute = indexService.getFlowRouteByPrimaryKey(flowTrans.getRouteId());
            //获取下序路线
            //FlowRoute nextFlowRoute = indexService.getNextFlowRouteByBefore(currentFlowRoute);
            //断下序申请数量是否为0，如果是0就可撤销
            if ((currentFlowRoute.getCheckNum() == null || currentFlowRoute.getCheckNum() == 0) || currentFlowRoute.getApplyNum() - currentFlowRoute.getCheckNum() >= flowTrans.getNum()) {
                return jsonResult(indexService.cancelApply(trans));
            }
            //如果不为0，则不可撤销
            else {
                return error("此转序已质检无法撤销申请！");
            }
        } else if (trans.getTranType().compareTo(2) == 0) {
            /** 派工转序 **/
            // 如果已经被质检
            AssemblyTransCheck transCheck = assemblyService.getTransSheetCheck(trans.getId());
            if (transCheck.getStatus() != 1 && transCheck.getStatus() != 4) {
                return error("此转序已质检无法撤销申请！");
            }
            //当前路线
            return jsonResult(assemblyService.cancelApply(trans.getId()));
        } else {
            return error("撤销发生错误，请重新撤销！");
        }
    }

    /**
     * 撤销质检
     */
    @ResponseBody
    @PostMapping("/cancel/check")
    public JsonResult cancelCheck(FlowTrans trans) {
        int cn = 0;
        if (trans.getTranType().compareTo(1) == 0) {
            /** 生产转序 **/
            cn = indexService.cancelCheck(trans);
        } else if (trans.getTranType().compareTo(2) == 0) {
            /** 装配转序 **/
            cn = assemblyService.cancelCheck(trans.getId());
        }
        return jsonResult(cn);
    }

//    /** 围猫 */
//    @GetMapping("/cat")
//    public String catchcat() {
//        return "catch";
//    }
//
//    @GetMapping("/test")
//    public String testPage() {
//        return "apply";
//    }

    /**
     * 返回首页
     */
    @GetMapping("/goIndex")
    public String goIndex() {
        return "index";
    }


}
